﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace COFE.Core.Logger
{
    public class EventDispatcher<T> : IEventDispatcher<T>
        where T : EventArgs
    {

        #region Constructor

        public EventDispatcher()
        {            
        }

        #endregion

        #region Methods

        public virtual IEventListener<T> SpawnListener(Action<object, T> onDispatch, bool register = true)
        {
            var retVal = new EventListener<T>(onDispatch);
            if (register)
                RegisterListener(retVal);
            return retVal;
        }

        public virtual void RegisterListener(IEventListener<T> listener)
        {
            lock (_registeredListeners)
                if (!_registeredListeners.Contains(listener))
                    _registeredListeners.Add(listener);
        }

        public virtual void UnregisterListener(IEventListener<T> listener)
        {
            lock (_registeredListeners)
                if (_registeredListeners.Contains(listener))
                    _registeredListeners.Remove(listener);
        }

        protected virtual bool matchListener(IEventListener<T> listener, T args)
        {
            return true;
        }

        public virtual void DispatchEvent(object sender, T args)
        {            
            COFEShared.MasterEventLogger.DispatchEvent(sender, args);
            foreach (var listener in _registeredListeners)
                if (matchListener(listener, args))
                    listener.DispatchEvent(sender, args);
        }

        #endregion

        #region Data

        protected List<IEventListener<T>> _registeredListeners = new List<IEventListener<T>>();

        #endregion

        #region Public Properties

              
        
        #endregion





    
    }
}
